<template>
  <div>
    <h2>流式数据</h2>
    <button @click="startStream">开始接收流</button>
    <div id="stream-data"></div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const streamData = ref([]);
const startStream = ()=> {
  console.log("进来没")
  const eventSource = new EventSource('http://127.0.0.1:8000/api/stream/');
  eventSource.onmessage = function(e) {
    console.log("收到没")
    document.getElementById('stream-data').innerHTML += `<p>${e.data}</p>`;
  };
  eventSource.onerror = function() {
    eventSource.close();
  };
}


// 使用 EventSource
// const eventSource = new EventSource('http://127.0.0.1:8000/api/stream/');
// eventSource.onmessage = (e) => {
//   console.log('收到数据:', e.data);
// };

// 或者使用 fetch API
// async function startStream() {
//   const response = await fetch('http://127.0.0.1:8000/api/stream/');
//   const reader = response.body.getReader();
//   const decoder = new TextDecoder();
//
//   while (true) {
//     const {done, value} = await reader.read();
//     if (done) break;
//     const chunk = decoder.decode(value);
//     console.log('收到数据块:', chunk);
//   }
// }



// const startStream = async () => {
//   try {
//     const response = await axios.get('http://localhost:8000/api/stream/', {
//       responseType: 'stream'  // 关键配置
//     });
//
//     const reader = response.data.getReader();
//     const decoder = new TextDecoder();
//
//     while (true) {
//       const { done, value } = await reader.read();
//       if (done) break;
//       const chunk = decoder.decode(value);
//       streamData.value.push(chunk.trim());
//     }
//   } catch (error) {
//     console.error('流式请求失败:', error);
//   }
// };
</script>

<style scoped>
.stream-box {
  height: 200px;
  overflow-y: scroll;
  border: 1px solid #eee;
}
</style>